﻿package com.snzflash.components.core 
{
	import flash.display.Stage;
	import flash.errors.IllegalOperationError;
	import flash.events.Event;
	/**
	 * Системный менеджер
	 * @author firsoff maxim, snzflash.com, tel: +79222345364, skype: maxim.firsoff
	 */
	public class SystemManager
	{
		static private var instance:SystemManager;
		 private var _stage:Stage;
		 private var _components:/*UIComponent*/Array;
		 private var _validateComponents:/*UIComponent*/Array;
		 private var _invalidated:Boolean;
		
		public function SystemManager() 
		{
			if (instance) throw new IllegalOperationError ( 'use [detInstance] method' );
		};
		
		
		public static function getInstance():SystemManager
		{
			if (!instance) instance = new SystemManager();
			return instance;
		};
		
		public  function addComponent(component:UIComponent):void 
		{
			if (!_components) _components = new Array();
			_components.push ( component );
			//var index:int = _components.indexOf(component);
		}
		
		public  function removeComponent(component:UIComponent):void 
		{
			if (!_components) return;
			var index:int = _components.indexOf(component);
			var index2:int = _validateComponents.indexOf(component);
			if( index2 != -1 ) _validateComponents.splice(index2, 1);
			if (index == -1) return;
			_components.splice(index, 1);
		};
		
		public function invalidate(component:UIComponent):void 
		{
			if ( !_validateComponents ) _validateComponents = [];
			_validateComponents.push(component);
			////trace(_invalidated, _stage);
			if (!_invalidated && _stage) 
			{
				////trace('invalidate');
				_invalidated = true;
				_stage.invalidate();
				_stage.addEventListener(Event.ENTER_FRAME, onStageRender);
				//onStageRender();
				////trace('invalidate');
			}
		};
		
		//private function onStageEF(event:Event):void 
		//{
			//_stage.removeEventListener(Event.ENTER_FRAME, onStageEF);
			//onStageRender();
		//};
		
		public function get stage():Stage { return _stage; };
		
		public function set stage(value:Stage):void 
		{
			if ( value == null) 
			{
				_stage.removeEventListener(Event.ENTER_FRAME, onStageRender);
				_stage.removeEventListener ( Event.RENDER , onStageRender);
				return;
			};
			if (_stage) 
			{
				return;
			}
			_stage = value;
			_stage.addEventListener ( Event.RENDER , onStageRender);
		};
		
		
		 private function onStageRender(event:Event = null):void 
		{
			_stage.removeEventListener(Event.ENTER_FRAME, onStageRender);
			if ( !_invalidated) return;
			for each(var i:UIComponent  in _validateComponents) 
			{
				i.validateNow();
			};
			
			
			////trace('onStageRender');
			_invalidated = false;
			_validateComponents = [];
		};
		
	}

}